package SocketTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

class ServerThread implements Runnable {
	Socket s = null;
	BufferedReader br = null;

	public ServerThread(Socket s) throws IOException {
		this.s = s;
		br = new BufferedReader(new InputStreamReader(s.getInputStream()));

	}

	public void run() {
		String content = null;
		try {
			while ((content = readFromClient()) != null) {
				for (Socket s : Server.socketlist) {
					PrintStream ps;
					ps = new PrintStream(s.getOutputStream());
					ps.println(content);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String readFromClient() {
		try {
			return br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Server.socketlist.remove(s);
		}
		return null;
	}
}


public class Server {


	public static ArrayList<Socket> socketlist = new ArrayList<Socket>();

	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(30000);
		while (true) {
			Socket s = ss.accept();
			socketlist.add(s);
			new Thread(new ServerThread(s)).start();
		}
	}
}
